package com.wen.jwtdemo.handler;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wen.jwtdemo.common.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String,Object> map = new HashMap<>();
        //从请求头里面获取token信息
        String authorization = request.getHeader("Authorization");
        try {
            DecodedJWT verify = JwtUtils.verify(authorization);
            String payload = verify.getPayload();
            System.out.println("payload"+payload);
            String name = verify.getClaim("name").asString();
            System.out.println(name);
            return true;
        }catch (SignatureVerificationException e){
            e.printStackTrace();
            map.put("msg", "无效签名");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("msg", "Token已经失效");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("msg", "算法不一致");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg", "token无效");
        }
        map.put("state",false);
        //将map 转为json  jackson
        String s = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(s);
        return false;
    }
}
